package cn.fintecher.pangolin.service.business.task;

import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.PaymentRecord;
import cn.fintecher.pangolin.entity.mysql.AssistCase;
import cn.fintecher.pangolin.entity.mysql.CaseInfo;
import cn.fintecher.pangolin.service.business.model.response.AppHomeResponse;
import cn.fintecher.pangolin.service.business.repository.elasticsearch.PaymentRecordElastic;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 14:45 2019/11/18
 */

@Service("appHomeTask")
public class AppHomeTask {
    @Autowired
    private PaymentRecordElastic paymentRecordElastic;

    /**
     * APP首页统计
     */
    @Async
    public CompletableFuture<AppHomeResponse> getHome(List<AssistCase> assistCases, String userId) {
        AppHomeResponse response = new AppHomeResponse();
        Double waitCollAmt = 0d; //欠款总金额
        Double hadPayAmt = 0d; //已还款金额
        Integer waitVisitNum = 0; //待外访任务数
        Integer hasVisitNum = 0; //已外访任务数
        Integer expireNum = 0; //即将到期数
        Integer nearThreeDays = 0; //近3天到期数
        List<String> caseIds = new ArrayList<>();
        for (AssistCase assistCase : assistCases) {
            caseIds.add(assistCase.getCaseId());
        }
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.termsQuery("caseId.keyword", caseIds)).must(QueryBuilders.matchPhraseQuery("flag", "0"));
        Iterable<PaymentRecord> iterable = paymentRecordElastic.search(builder);
        List<PaymentRecord> paymentRecords = IterableUtils.toList(iterable);
        for (AssistCase assistCase : assistCases) {
            String dateStr = ZWDateUtil.fomratterDate(assistCase.getVisitTimeEnd(), "yyyy-MM-dd");
            if (dateStr.equals(ZWDateUtil.fomratterDate(new Date(), "yyyy-MM-dd"))) {
                expireNum++;
            }
            Period p = new Period(new DateTime(ZWDateUtil.getNowDate()), new DateTime(dateStr), PeriodType.days());
            if (p.getDays() <= 3 && p.getDays() >= 0) {
                nearThreeDays++;
            }
            if (StringUtils.isBlank(assistCase.getLastContactResult())) {
                waitVisitNum++;
            } else {
                hasVisitNum++;
            }
            //计算欠款总金额和已还款金额
            waitCollAmt += assistCase.getLeftAmt();
            if (!paymentRecords.isEmpty()) {
                List<PaymentRecord> list = paymentRecords.stream().filter(e -> e.getCaseId().equals(assistCase.getCaseId()) && Objects.nonNull(e.getAssistCollector()) && e.getAssistCollector().equals(userId)).collect(Collectors.toList());
                if (!list.isEmpty()) {
                    Double amt = list.stream().mapToDouble(PaymentRecord::getPaymentAmt).sum();
                    hadPayAmt += amt;
                }
            }
        }
        response.setWaitCollAmt(waitCollAmt); //欠款总金额
        response.setHadPayAmt(hadPayAmt); //已还款金额
        response.setVisitNum(assistCases.size()); //总外访任务数
        response.setWaitVisitNum(waitVisitNum); //待外访任务数
        response.setHasVisitNum(hasVisitNum); //已外访任务数
        response.setExpireNum(expireNum); //即将到期数
        response.setNearThreeDays(nearThreeDays); //近3天到期数
        return CompletableFuture.completedFuture(response);
    }

    @Async
    public CompletableFuture<AppHomeResponse> getHomeOut(List<CaseInfo> caseInfos, String userId) {
        AppHomeResponse response = new AppHomeResponse();
        Double waitCollAmt = 0d; //欠款总金额
        Double hadPayAmt = 0d; //已还款金额
        Integer waitOutNum = 0; //待外访数
        Integer hasOutNum = 0; //已外访数
        List<String> caseIds = new ArrayList<>();
        for (CaseInfo caseInfo : caseInfos) {
            caseIds.add(caseInfo.getId());
        }
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.termsQuery("caseId.keyword", caseIds)).must(QueryBuilders.matchPhraseQuery("flag", "0"));
        Iterable<PaymentRecord> iterable = paymentRecordElastic.search(builder);
        List<PaymentRecord> paymentRecords = IterableUtils.toList(iterable);
        for (CaseInfo caseInfo : caseInfos) {
            if (Objects.isNull(caseInfo.getLastContactResult())) {
                waitOutNum++;
            } else {
                hasOutNum++;
            }
            //计算欠款总金额和已还款金额
            waitCollAmt += caseInfo.getLeftAmt();
            if (!paymentRecords.isEmpty()) {
                List<PaymentRecord> list = paymentRecords.stream().filter(e -> e.getCaseId().equals(caseInfo.getId()) && Objects.nonNull(e.getCurrentCollector()) && e.getCurrentCollector().equals(userId)).collect(Collectors.toList());
                if (!list.isEmpty()) {
                    Double amt = list.stream().mapToDouble(PaymentRecord::getPaymentAmt).sum();
                    hadPayAmt += amt;
                }
            }
        }
        response.setWaitCollAmt(waitCollAmt); //欠款总金额
        response.setHadPayAmt(hadPayAmt); //已还款金额
        response.setOutNum(caseInfos.size()); //总外访任务数
        response.setWaitOutNum(waitOutNum); //待外访任务数
        response.setHasOutNum(hasOutNum); //已外访任务数
        return CompletableFuture.completedFuture(response);
    }
}
